package org.kent.w.base.common.executor;

import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 线程池
 *
 * @author wu.jigang@geely.com
 * @version 1.0
 * @Date :Created by 2020/3/5.
 */
public class ExecutorUtil {

    public static <V> TraceableCallable<V> newCallableThread(Supplier<V> supplier) {
        return new TraceableCallable<V>() {
            @Override
            public V process() {
                return supplier.get();
            }
        };
    }

    public static  TraceableRunnable newRunnableThread(Supplier<Void> supplier) {
        return new TraceableRunnable() {
            @Override
            public void process() {
                supplier.get();
            }
        };
    }

    /***
     * 线程池是否关闭
     * @param executor
     * @return
     */
    public static boolean isShutdown(Executor executor) {
        return executor instanceof ExecutorService && ((ExecutorService) executor).isShutdown();
    }

    /***
     * 线程池优雅关停
     * @param executor 线程池
     * @param timeout  超时时间(豪秒)
     */
    public static void gracefulShutdown(Executor executor, int timeout) {

        if (executor instanceof ExecutorService && !isShutdown(executor)) {
            ExecutorService es = (ExecutorService) executor;

            try {

                es.shutdown();
            } catch (Exception ex) {
                return;
            }

            try {
                if (!es.awaitTermination((long) timeout, TimeUnit.MILLISECONDS)) {
                    es.shutdownNow();
                }
            } catch (InterruptedException e) {
                es.shutdownNow();
                //Thread.currentThread().interrupt();
            }

        }
    }
}
